package com.hyacinth.common.framework;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.hyacinth.common.constant.PersistResult;
import com.hyacinth.common.framework.i.IControllerSupport;

public abstract class ControllerSupport<D extends Domain> extends Generic<D> implements IControllerSupport<D>, Serializable {

	private static final long serialVersionUID = -1908530494549635538L;
	

	protected String printOut(int result, String msg) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", result);
		map.put("msg", msg);
		return JSON.toJSONString(map);
	}
	
	@RequestMapping("list.do")
	public @ResponseBody String list() throws Exception {
		//return DateGrid.getData(getService().all(), parameter, getFields());
		return JSON.toJSONString(getService().all());
	}
	
	@RequestMapping("delete.do")
	protected @ResponseBody String delete(@RequestParam Long id) {
		try {
			if(id!=null) {
				D m = getService().find(id);
				getService().feignRemove(m);
			}
		}catch(Exception e) {
			e.printStackTrace();
			return printOut(PersistResult.ERROR, PersistResult.MSG_ERROR);
		}
		return printOut(PersistResult.SUCCESS, PersistResult.MSG_SUCCESS);
	}
	
	@RequestMapping("saveOrUpdate.do")
	protected @ResponseBody String saveOrUpdate(@ModelAttribute D d) {
		try {
			if(d.getId()==null) {
				getService().persist(d);
			}else {
				getService().merge(d);
			}
		}catch(Exception e) {
			e.printStackTrace();
			return printOut(PersistResult.ERROR, PersistResult.MSG_ERROR);
		}
		return printOut(PersistResult.SUCCESS, PersistResult.MSG_SUCCESS);
	}
}
